package com.smile.auth.web;


import com.alibaba.fastjson.TypeReference;
import com.smile.auth.feign.MemberFeignService;
import com.smile.auth.feign.ThreadPartyFeignService;
import com.smile.auth.vo.UserLoginVo;
import com.smile.auth.vo.UserRegisterVo;
import com.smile.common.exception.BizCodeEnum;
import com.smile.common.utils.R;
import com.smile.common.vo.MemberResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.smile.common.constant.AuthServerConstant.LOGIN_USER;

/**
 * 验证码防刷(同手机号)
 * 注册功能
 * 登录功能
 */


@Controller
public class LoginServerController {
    @Autowired
    ThreadPartyFeignService feignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    MemberFeignService memberFeignService;

    //返回登录页
    @GetMapping({"/","login.html"})
    public String loginServer(){
        return "index";
    }
    //返回注册页
    @GetMapping("/reg.html")
    public String regServer(){
        return "reg";
    }
    //验证码
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone){
        //验证码防刷（1分钟内）
        String s = redisTemplate.opsForValue().get(LOGIN_USER + phone);
        if(s!=null) {
            long l = Long.parseLong(s.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }else {
            //redis缓存验证码
            String code = UUID.randomUUID().toString().substring(0, 5);
            String codeRedis = code + "_" + System.currentTimeMillis();
            redisTemplate.opsForValue().set(LOGIN_USER + phone,
                     codeRedis,
                    10, TimeUnit.MINUTES);
            feignService.sendCode(phone, code);
        }
        return R.ok();
    }
    //RedirectAttributes 类似与model帮助重定向返回数据
    //注册功能
   @PostMapping("/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result,
                           RedirectAttributes redirectAttributes){
        if(result.hasErrors()){
            //获取错误字段的错误信息进行封装map
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(fieldError -> {
                return fieldError.getField();
            }, fieldError -> {
                return fieldError.getDefaultMessage();
            }));
            //返回错误信息
            System.out.println(errors);
            redirectAttributes.addFlashAttribute("errors",errors);
            //
            return "redirect:http://auth.smile.com/reg.html";
        }

        //校验验证码
       String code = redisTemplate.opsForValue().get(LOGIN_USER + vo.getPhone());
        if(!StringUtils.isEmpty(code)){
          if(vo.getCode().equals(code.split("_")[0])){
              //删除验证码
              redisTemplate.delete(LOGIN_USER + vo.getPhone());
              //验证码正确,调用远程服务进行注册
              R register = memberFeignService.register(vo);
              if(register.getCode()==0){
                  //成功
                  return "redirect:http://auth.smile.com/";
              }else {
                  //失败
                  Map<Object, Object> map = new HashMap<>();
                  map.put("msg",register.getData("msg",new TypeReference<String>(){}));
                  redirectAttributes.addFlashAttribute("errors",map);
                  return "redirect:http://auth.smile.com/reg.html";
              }

          }else {
              Map<Object, Object> map = new HashMap<>();
              map.put("errors","验证码错误");
              redirectAttributes.addFlashAttribute("errors",map);
              return "redirect:http://auth.smile.com/reg.html";
          }
        }else {
            Map<Object, Object> map = new HashMap<>();
            map.put("errors","验证码错误");
            redirectAttributes.addFlashAttribute("errors",map);
            return "redirect:http://auth.smile.com/reg.html";
        }
    }
    //登录功能
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        //远程调用member服务,判断用户信息
        R login = memberFeignService.login(vo);
        if(login.getCode()==0) {
            MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {});
            session.setAttribute(LOGIN_USER,data);
            //成功返回首页
            return "redirect:http://smile.com/";
        }else {
            Map<String, String> map = new HashMap<>();
            map.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",map);
            return "redirect:http://auth.smile.com/";
        }

    }

}
